using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Collections;

/// <summary>
/// Summary description for Workflow
/// </summary>
public class Workflow
{
    DataSet dsWorkflow = new DataSet();
    HDDatabase HDD = new HDDatabase();
    string[] master_objects = new string[] { "sy_workflow_ruleset", "sy_workflow_triggers" };
    string[] child_objects = new string[] { "sy_workflow_rules", "sy_field_updates" };//, "sy_work_item"
    string strPagesetRowId = "";
    string strMenuRowId = "";
    string sWorkitem_User = "";
    DataRow drCurrentData = null;
    DataRow drRuleChange = null;
    public Workflow()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    public bool BeginWorkflow(ref DataSet PageInfo, ref DataSet InputInfo, string Operation)
    {
        getRuleset();
        if (dsWorkflow.Tables.Contains("sy_workflow_ruleset"))
            if (dsWorkflow.Tables.Contains("sy_workflow_rules"))
                triggerWorkflow(ref PageInfo, ref InputInfo, Operation);
        dsWorkflow.Dispose();
        dsWorkflow = null;
        return true;
    }

    private void getRuleset()
    {
        try
        {
            string sSql = "select * from sy_usr";
            dsWorkflow.Tables.Add(HDD.GetDataTable(sSql, "sy_usr").Copy());
            sSql = "select * from sy_org_structure";
            dsWorkflow.Tables.Add(HDD.GetDataTable(sSql, "sy_org_structure").Copy());
            sSql = "select * from sy_obj";
            dsWorkflow.Tables.Add(HDD.GetDataTable(sSql, "sy_obj").Copy());
            sSql = "select * from sy_obj_att";
            dsWorkflow.Tables.Add(HDD.GetDataTable(sSql, "sy_obj_att").Copy());
            sSql = "select * from sy_workflow_rules";
            dsWorkflow.Tables.Add(HDD.GetDataTable(sSql, "rules").Copy());

            string sTitle = null;
            if (dsWorkflow.Tables["sy_usr"] != null)
            {
                DataRow[] drr = dsWorkflow.Tables["sy_usr"].Select("af_row_id='" + HttpContext.Current.Session["user_afrowid"].ToString() + "'");
                if (drr.Length > 0)
                {
                    sTitle = drr[0]["title"].ToString();
                    //sTitle = getColumnValue("sy_org_structure", "af_row_id", sTitle, "title");
                }
            }
            //sSql = "select * from sy_workflow_rules where source_title ='" + sTitle + "' or source_title = '" + HttpContext.Current.Session["userid"].ToString() + "'";
            sSql = "select * from sy_workflow_rules where source_title ='" + sTitle + "' or source_title = '" + HttpContext.Current.Session["user_afrowid"].ToString() + "'";

            dsWorkflow.Tables.Add(HDD.GetDataTable(sSql, "sy_workflow_rules").Copy());
            if (dsWorkflow.Tables["sy_workflow_rules"].Rows.Count > 0)
            {
                getChildRecords();
                getMasterRecords();
            }
            //sSql = "select * from sy_workflow_history";
            //dsWorkflow.Tables.Add(HDD.GetDataTable(sSql, "sy_workflow_history").Copy());
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("getRuleset : Error :" + ex.Message);
        }
    }

    private void getMasterRecords()
    {
        try
        {
            string sSql = null;
            string sKeyValues = "";
            foreach (DataRow dr in dsWorkflow.Tables["sy_workflow_rules"].Rows)
            {
                sKeyValues += "'" + dr["ruleset"].ToString() + "',";
            }
            if (sKeyValues.EndsWith(",")) sKeyValues = sKeyValues.Remove(sKeyValues.Length - 1);
            sSql = "select * from sy_workflow_ruleset where af_row_id in (" + sKeyValues + ")";
            dsWorkflow.Tables.Add(HDD.GetDataTable(sSql, "sy_workflow_ruleset").Copy());
            sSql = "select * from sy_workflow_triggers where ruleset_id in (" + sKeyValues + ")";
            dsWorkflow.Tables.Add(HDD.GetDataTable(sSql, "sy_workflow_triggers").Copy());
            sSql = "select * from sy_workflow_history where ruleset_id in (" + sKeyValues + ")";
            dsWorkflow.Tables.Add(HDD.GetDataTable(sSql, "sy_workflow_history").Copy());
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("getMasterRecords : Error :" + ex.Message);
        }
    }

    private void getChildRecords()
    {
        try
        {
            string sSql = null;
            string sKeyValues = "";
            foreach (DataRow dr in dsWorkflow.Tables["sy_workflow_rules"].Rows)
            {
                sKeyValues += "'" + dr["af_row_id"].ToString() + "',";
            }
            if (sKeyValues.EndsWith(",")) sKeyValues = sKeyValues.Remove(sKeyValues.Length - 1);
            sSql = "select * from sy_work_item where rule_id in (" + sKeyValues + ")";
            dsWorkflow.Tables.Add(HDD.GetDataTable(sSql, "sy_work_item").Copy());
            sSql = "select * from sy_field_updates where rule_id in (" + sKeyValues + ")";
            dsWorkflow.Tables.Add(HDD.GetDataTable(sSql, "sy_field_updates").Copy());
            sSql = "select * from sy_workflow_history where rule_id in (" + sKeyValues + ")";
            dsWorkflow.Tables.Add(HDD.GetDataTable(sSql, "sy_workflow_history").Copy());
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("getChildRecords : Error :" + ex.Message);
        }
    }

    private bool checkEventOperation(string Event, string Operation)
    {
        bool bReturn = false;

        switch (Event)
        {
            case "RC":
                if (Operation == "INSERT")
                    bReturn = true;
                break;
            case "RCU":
            case "RCUO":
            case "RCUNAP":
            case "RCUSTEL":
            case "RCUBOR":
            case "RCUBORSTEL":
                if (Operation == "INSERT" || Operation == "UPDATE")
                    bReturn = true;
                break;
        }

        return bReturn;
    }

    private void triggerWorkflow(ref DataSet PageInfo, ref DataSet InputInfo, string Operation)
    {
        try
        {
            strPagesetRowId = HttpContext.Current.Request.QueryString["pgs_id"];
            strMenuRowId = getValueFromDB("sy_mnu", "pageset_id", "af_row_id", strPagesetRowId);

            foreach (DataRow dr in dsWorkflow.Tables["sy_workflow_ruleset"].Rows)
            {
                if (!checkEventOperation(dr["event"].ToString(), Operation)) continue;

                string sSql = "select object_id from sy_obj where af_row_id='" + dr["object_id"].ToString() + "'";
                string sObject_Id = getColumnValue("sy_obj", "af_row_id", dr["object_id"].ToString(), "object_id");  //HDD.GetColumnValue(sSql);

                DataRow[] drr = PageInfo.Tables["Page"].Select("");// ("object_id ='" + sObject_Id + "'");
                for (int iRowCount = 0; iRowCount < drr.Length; iRowCount++)
                {
                    string sWorkflow_Objectid = drr[iRowCount]["object_id"].ToString().ToLower();
                    DataTable dtData = InputInfo.Tables[drr[iRowCount]["page_id"].ToString()].Copy();
                    dtData.TableName = "workflow_data_temp";

                    if (dsWorkflow.Tables.Contains("workflow_data_temp"))
                        dsWorkflow.Tables.Remove("workflow_data_temp");

                    dsWorkflow.Tables.Add(dtData.Copy());
                    string sCondition = getCondition(PageInfo, InputInfo, dr["af_row_id"].ToString(), drr[iRowCount]["page_id"].ToString());
                    string Based_on = dr["based_on"].ToString().ToLower();
                    //strPagesetRowId = HttpContext.Current.Request.QueryString["pgs_id"];
                    //strMenuRowId = getValueFromDB("sy_mnu", "pageset_id", "menu_id", strPagesetRowId);
                    if (sObject_Id.ToLower() != sWorkflow_Objectid && dr["apply_for_childs"].ToString().ToLower() == "true")
                    {
                        string sObject_id = drr[iRowCount]["object_id"].ToString();
                        string sObject_afrowid = getColumnValue("sy_obj", "object_id", sObject_id, "af_row_id");
                        Hashtable hsMaster = isChildBeingEdited(ref PageInfo, sObject_Id, sObject_afrowid, dr);
                        if (hsMaster != null)
                        {
                            sWorkflow_Objectid = getColumnValue("sy_obj", "af_row_id", hsMaster["masterobject"].ToString(), "object_table").ToLower();
                            string sPgs_id = getPageset(hsMaster["masterobject"].ToString());

                            DataTable dtMasterData = HDD.GetDataTable("select * from " + sWorkflow_Objectid);

                            DataSet dsTempData = new DataSet();
                            dtMasterData.TableName = drr[iRowCount]["page_id"].ToString();
                            dsTempData.Tables.Add(dtMasterData.Copy());

                            dtMasterData.TableName = "workflow_data_temp";

                            if (dsWorkflow.Tables.Contains("workflow_data_temp"))
                                dsWorkflow.Tables.Remove("workflow_data_temp");

                            dsWorkflow.Tables.Add(dtMasterData.Copy());

                            if (sPgs_id.Trim() != "")
                            {
                                PageInfoLoad objPIL = new PageInfoLoad();
                                DataSet dsTempPgs = objPIL.GetPageSetPageCtrlInfo(sPgs_id);
                                objPIL = null;

                                sCondition = getCondition(dsTempPgs, dsTempData, dr["af_row_id"].ToString(), drr[iRowCount]["page_id"].ToString());

                                dsTempPgs.Dispose();
                                dsTempPgs = null;
                            }
                            dsTempData.Dispose();
                            dsTempData = null;

                            foreach (DataRow drData in dtData.Rows)
                            {
                                DataRow[] drMaster = null;
                                if (sCondition.Trim() != "")
                                    drMaster = dtMasterData.Select("af_row_id='" + drData[hsMaster["masterfield"].ToString()].ToString() + "' and " + sCondition);
                                else
                                    drMaster = dtMasterData.Select("af_row_id='" + drData[hsMaster["masterfield"].ToString()].ToString() + "'");

                                if (drMaster.Length > 0)
                                    checkRules(dr["af_row_id"].ToString(), hsMaster["masterobject"].ToString(), ref drMaster, Operation, Based_on);
                            }
                            dtMasterData.Dispose();
                            dtMasterData = null;
                        }
                    }
                    else
                    {
                        if (sObject_Id.ToLower() == sWorkflow_Objectid)
                        {
                            strPagesetRowId = HttpContext.Current.Request.QueryString["pgs_id"];
                            //strPagesetRowId = getValueFromDB("sy_pgs", "pageset_id", "af_row_id", HttpContext.Current.Request.QueryString["pgs_id"]);
                            //strMenuRowId = getValueFromDB("sy_mnu", "menu_id", "af_row_id", strMenuRowId);
                            dtData = dsWorkflow.Tables["workflow_data_temp"].Copy();
                            DataRow[] drInput = dtData.Select(sCondition);//InputInfo.Tables[drr[iRowCount]["page_id"].ToString()].Select(sCondition);

                            if (drInput.Length > 0)
                            {
                                //if (dr["based_on"].ToString().ToLower() == "title" || dr["based_on"].ToString().ToLower() == "")
                                checkRules(dr["af_row_id"].ToString(), dr["object_id"].ToString(), ref drInput, Operation, Based_on);
                                //else if (dr["based_on"].ToString().ToLower() == "user")
                            }
                        }
                    }
                    dtData.Dispose();
                    dtData = null;
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("triggerWorkflow : Error :" + ex.Message);
        }
    }

    private Hashtable isChildBeingEdited(ref DataSet dsPage, string objectId, string objectAF_Row_ID, DataRow drWorkFlowRuleset)//March 30 2008
    {
        Hashtable htMasterDetails = null;
        DataSet dsMasDetail = new DataSet();
        //DataSet dsObj = new DataSet();
        try
        {
            dsMasDetail = HDD.GetDataset("select * from sy_obj_mas_detail");//gets all the sy_obj_mas records
            //dsObj = HDD.GetDataset("select * from sy_obj");//gets all the sy_obj records
            string masterObject = _checkForChildEdit(dsMasDetail, objectAF_Row_ID, drWorkFlowRuleset["object_id"].ToString());//gets the master object's af_row_id
            if (masterObject != "")
            {
                htMasterDetails = new Hashtable();
                htMasterDetails.Add("masterobject", masterObject);//store master object
                string sCondn = "object_id='" + objectAF_Row_ID + "' and master_obj='" + dsWorkflow.Tables["sy_obj"].Select("af_row_id='" + masterObject + "'")[0]["object_id"].ToString() + "'";
                htMasterDetails.Add("masterfield", dsMasDetail.Tables[0].Select(sCondn)[0]["attrib_id"].ToString());//store master object's field
            }
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("isChildBeingEdited : Error :" + e.Message);
        }
        finally
        {
            dsMasDetail = null;
            //dsObj = null;     
        }
        return htMasterDetails;
    }
    private string _checkForChildEdit(DataSet dsMasDetail, string objectAF_Row_ID, string workFlowObject)//march 30 2008
    {
        //Hashtable htObjectAndAtrribute = new Hashtable();
        string ret = "";
        ArrayList alMasters = new ArrayList();//stores all the master objects for an object
        foreach (DataRow dr in dsMasDetail.Tables[0].Select("object_id ='" + objectAF_Row_ID + "'"))//check for masters
        {
            alMasters.Add(dsWorkflow.Tables["sy_obj"].Select("object_id ='" + dr["master_obj"].ToString() + "'")[0]["af_row_id"].ToString());//stores af_row_id of master object
            //htObjectAndAtrribute.Add("MasterObject", dsObj.Tables[0].Select("object_id ='" + dr["master_obj"].ToString() + "'")[0]["af_row_id"].ToString());
            //htObjectAndAtrribute.Add("Attribute", dr["attrib_id"].ToString());
        }
        for (int i = 0; i < alMasters.Count; i++)
        {
            //foreach (DataRow dr in dsWorkflow.Tables["sy_workflow_ruleset"].Rows)
            //{
            //    if (alMasters[i].ToString() == dr["object_id"].ToString())//match
            //        return true;
            //}
            if (alMasters[i].ToString() == workFlowObject)//if master object and work flow object matches
            {
                ret = alMasters[i].ToString();
                return alMasters[i].ToString();
            }
        }
        for (int j = 0; j < alMasters.Count; j++)//for no match
        {
            ret = _checkForChildEdit(dsMasDetail, alMasters[j].ToString(), workFlowObject);//check for the corresponding upper level master object
            if (ret != "") break;
        }
        return ret;
    }

    private void changeDatacolumnDatatype(DataSet InputInfo, string Datatype, string PageId, string Columnname)
    {
        try
        {
            //DataTable dtTemp = InputInfo.Tables[PageId].Clone();
            DataTable dtTemp = dsWorkflow.Tables["workflow_data_temp"].Clone();
            dtTemp.Columns[Columnname].DataType = System.Type.GetType(Datatype);

            foreach (DataRow dr in InputInfo.Tables[PageId].Rows)
            {
                if (dr[Columnname].ToString() == "")
                    dr[Columnname] = 0;
                dtTemp.ImportRow(dr);
            }

            if (dsWorkflow.Tables.Contains("workflow_data_temp"))
            {
                dsWorkflow.Tables.Remove("workflow_data_temp");
                dtTemp.TableName = "workflow_data_temp";
                dsWorkflow.Tables.Add(dtTemp.Copy());
            }
            dtTemp.Dispose();
            dtTemp = null;
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("changeDatacolumnDatatype : Error :" + ex.Message);
        }
    }

    private string getCondition(DataSet PageInfo, DataSet InputInfo, string Ruleset_Id, string PageId)
    {
        string sCondition = "";
        try
        {
            DataRow[] drr = dsWorkflow.Tables["sy_workflow_triggers"].Select("ruleset_id='" + Ruleset_Id + "'", "sequence asc");
            if (drr.Length > 0)
            {
                for (int iRowCount = 0; iRowCount < drr.Length; iRowCount++)
                {
                    if (PageInfo.Tables["PageCtrl"].Select("control_id = '" + drr[iRowCount]["field"].ToString() + "'").Length > 0)
                    {
                        string sDatatype = PageInfo.Tables["PageCtrl"].Select("control_id = '" + drr[iRowCount]["field"].ToString() + "'")[0]["control_attrib_type"].ToString();

                        string sQuoteIdentifier = "";

                        //DataColumn dc = new DataColumn();
                        switch (sDatatype)
                        {
                            case "BO":
                            case "DA":
                            case "DT":
                            case "TX":
                                sQuoteIdentifier = "'";
                                break;
                            case "CU":
                            case "DC":
                                changeDatacolumnDatatype(InputInfo, "System.Decimal", PageId, drr[iRowCount]["field"].ToString());
                                //dc.DataType = System.Type.GetType("system.decimal");
                                break;
                            case "NU":
                            case "AN":
                                changeDatacolumnDatatype(InputInfo, "System.Int32", PageId, drr[iRowCount]["field"].ToString());
                                //dc.DataType = System.Type.GetType("system.int32");
                                break;
                        }

                        if (iRowCount == drr.Length - 1)
                            sCondition += drr[iRowCount]["field"].ToString() + " " + drr[iRowCount]["operator"].ToString().Replace("'", "").Replace("%C%", sQuoteIdentifier + drr[iRowCount]["value"].ToString().Replace("'", "''") + sQuoteIdentifier);
                        else
                            sCondition += drr[iRowCount]["field"].ToString() + " " + drr[iRowCount]["operator"].ToString().Replace("'", "").Replace("%C%", sQuoteIdentifier + drr[iRowCount]["value"].ToString().Replace("'", "''") + sQuoteIdentifier) + " " + drr[iRowCount]["and_or"].ToString() + " ";
                    }
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("getCondition : Error :" + ex.Message);
        }
        return sCondition;
    }

    private string getCondition(string Ruleset_Id)
    {
        string sCondition = "";
        try
        {
            DataRow[] drr = dsWorkflow.Tables["sy_workflow_triggers"].Select("ruleset_id='" + Ruleset_Id + "'", "sequence asc");
            if (drr.Length > 0)
            {
                for (int iRowCount = 0; iRowCount < drr.Length; iRowCount++)
                {
                    if (iRowCount == drr.Length - 1)
                        sCondition += drr[iRowCount]["field"].ToString() + " " + drr[iRowCount]["operator"].ToString().Replace("%C%", drr[iRowCount]["value"].ToString().Replace("'", "''"));
                    else
                        sCondition += drr[iRowCount]["field"].ToString() + " " + drr[iRowCount]["operator"].ToString().Replace("%C%", drr[iRowCount]["value"].ToString().Replace("'", "''")) + " " + drr[iRowCount]["and_or"].ToString() + " ";
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("getCondition : Error :" + ex.Message);
        }
        return sCondition;
    }

    private bool checkForRCUO(string Ruleset_id, string Rule_Id, string KeyValue, string Operation)
    {
        bool bReturn = false;
        try
        {
            string sSql = "select * from sy_workflow_history where ruleset_id='" + Ruleset_id + "' and rule_id='" + Rule_Id + "' and key_value='" + KeyValue + "'";

            DataTable dt = HDD.GetDataTable(sSql);

            if (dt.Rows.Count == 0)
                bReturn = true;

            dt.Dispose();
            dt = null;
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("checkForRCUO : Error :" + ex.Message);
        }
        return bReturn;
    }

    private void getPageInfo(ref DataSet dsPageInfo)
    {
        PageInfoLoad PIL = new PageInfoLoad();
        dsPageInfo = PIL.GetPageSetPageCtrlInfo("7eec6ff1641256a2"); // workitem_user
        PIL = null;
    }

    private bool checkForRCUBOR(string Ruleset_id, string Rule_Id, string KeyValue, string Operation)
    {
        bool bReturn = false;
        try
        {
            if (drCurrentData["created_by"].ToString() == HttpContext.Current.Session["user_afrowid"].ToString())
                bReturn = true;
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("checkForRCUSTEL : Error :" + ex.Message);
        }
        return bReturn;
    }

    private bool checkForRCUBORSTEL(string Ruleset_id, string Rule_Id, string KeyValue, string Operation)
    {
        bool bReturn = false;
        try
        {
            if (drCurrentData["created_by"].ToString() == HttpContext.Current.Session["user_afrowid"].ToString())
            {
                string sSql = "delete sy_workitem_user where ruleset_id='" + Ruleset_id + "' and rule_id='" + Rule_Id + "' and key_value='" + KeyValue + "' and is_active='1'";
                SqlCommand sqlComm = new SqlCommand(sSql);
                int iRet = HDD.ExecuteCmdObj(sqlComm);
                sSql = "update sy_workitem_user set is_active='0' where ruleset_id='" + Ruleset_id + "' and key_value='" + KeyValue + "'";
                sqlComm = new SqlCommand(sSql);
                iRet = HDD.ExecuteCmdObj(sqlComm);
                sqlComm = null;
                bReturn = true;
            }
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("checkForRCUBORSTEL : Error :" + ex.Message);
        }
        return bReturn;
    }


    private bool checkForRCUSTEL(string Ruleset_id, string Rule_Id, string KeyValue, string Operation)
    {
        bool bReturn = true;
        try
        {
            string sSql = "delete sy_workitem_user where ruleset_id='" + Ruleset_id + "' and rule_id='" + Rule_Id + "' and key_value='" + KeyValue + "' and is_active='1'";
            SqlCommand sqlComm = new SqlCommand(sSql);
            int iRet = HDD.ExecuteCmdObj(sqlComm);
            sSql = "update sy_workitem_user set is_active='0' where ruleset_id='" + Ruleset_id + "' and key_value='" + KeyValue + "'";
            sqlComm = new SqlCommand(sSql);
            iRet = HDD.ExecuteCmdObj(sqlComm);
            sqlComm = null;
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("checkForRCUSTEL : Error :" + ex.Message);
        }
        return bReturn;
    }

    private bool checkForRCUNAP(string Ruleset_id, string Rule_Id, string KeyValue, string Operation)
    {
        bool bReturn = false;
        try
        {
            string sSql = "ruleset_id='" + Ruleset_id + "' and rule_id='" + Rule_Id + "' and key_value='" + KeyValue + "'";

            DataRow[] drr = dsWorkflow.Tables["sy_workflow_history"].Select(sSql, "created_at desc");

            if (drr.Length > 0)
            {
                if (drr[0]["status"].ToString().ToLower() == "completed" || drr[0]["status"].ToString().ToLower() == "closed")
                    bReturn = true;
            }
            else
                bReturn = true;
            drr = null;
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("checkForRCUNAP : Error :" + ex.Message);
        }
        return bReturn;
    }

    private void checkRules(string Ruleset_Id, string Object_Id, ref DataRow[] drInfo, string Operation, string Based_On)
    {
        try
        {
            string sCurrentUserTitle = getColumnValue("sy_usr", "af_row_id", HttpContext.Current.Session["user_afrowid"].ToString(), "title");
            //sCurrentUserTitle = getColumnValue("sy_org_structure", "af_row_id", sCurrentUserTitle, "title");
            string sReportingTo = getColumnValue("sy_usr", "af_row_id", HttpContext.Current.Session["user_afrowid"].ToString(), "reporting_to");
            string sReportingToTitle = getColumnValue("sy_usr", "af_row_id", sReportingTo, "title");
            //sReportingToTitle = getColumnValue("sy_org_structure", "af_row_id", sReportingToTitle, "title");
            string sRule_id = getColumnValue("sy_workflow_rules", "ruleset='" + Ruleset_Id + "' and sequence", "0", "af_row_id");
            string sTarget = getColumnValue("sy_workflow_rules", "af_row_id", sRule_id, "Target").ToLower();
            /*if (sTarget == "title")
            {
                Based_On = "title";
            }
            else if (sTarget == "user")
            {
                Based_On = "user";
            }
            else */
            //if (sTarget == "user_from_field") // commanded by 'Imran Gani' on 21-Mar-2013
            //{
            //    Based_On = "title";
            //}

            DataRow[] drr = null;
            if (Based_On == "title" || sTarget == "user_from_field")
            {
                string sSkip_Rule = getColumnValue("sy_workflow_ruleset", "af_row_id", Ruleset_Id, "skip_title").ToLower();
                if (sTarget == "user_from_field" || sTarget == "user") // Modified by 'Imran Gani' on 27-Mar-2013, to compare with target user.
                {
                    //sSkip_Rule = "true";
                    if (Based_On == "user") // Added by 'Imran Gani' on 21-Mar-2013, to create a workitem for 'user from field'
                        drr = dsWorkflow.Tables["sy_workflow_rules"].Select("ruleset='" + Ruleset_Id + "' and sequence=0 and source_title='" + getColumnValue("sy_usr", "title", sCurrentUserTitle, "af_row_id") + "'");
                    else
                        drr = dsWorkflow.Tables["sy_workflow_rules"].Select("ruleset='" + Ruleset_Id + "' and sequence=0 and source_title='" + sCurrentUserTitle + "'");
                }
                else if (sSkip_Rule == "true")
                    drr = dsWorkflow.Tables["sy_workflow_rules"].Select("ruleset='" + Ruleset_Id + "' and sequence=0 and source_title='" + sCurrentUserTitle + "'");
                else if (sSkip_Rule == "false" || sSkip_Rule == "")
                    drr = dsWorkflow.Tables["sy_workflow_rules"].Select("ruleset='" + Ruleset_Id + "' and sequence=0 and source_title='" + sCurrentUserTitle + "' and target_title='" + sReportingToTitle + "'");
            }
            else if (Based_On == "user")
                drr = dsWorkflow.Tables["sy_workflow_rules"].Select("ruleset='" + Ruleset_Id + "' and sequence=0 and source_title='" + HttpContext.Current.Session["user_afrowid"].ToString() + "'");

            if (drr.Length > 0)
            {
                for (int iRowCount = 0; iRowCount < drr.Length; iRowCount++)
                {
                    foreach (DataRow dr in drInfo)
                    {
                        drCurrentData = dr;
                        bool bHis = true;
                        string sEvent = getColumnValue("sy_workflow_ruleset", "af_row_id", Ruleset_Id, "Event");
                        switch (sEvent)
                        {
                            case "RCUO":
                                bHis = false;
                                bHis = checkForRCUO(Ruleset_Id, drr[iRowCount]["af_row_id"].ToString(), dr["af_row_id"].ToString(), Operation);
                                break;
                            case "RCUNAP":
                                bHis = false;
                                bHis = checkForRCUNAP(Ruleset_Id, drr[iRowCount]["af_row_id"].ToString(), dr["af_row_id"].ToString(), Operation);
                                break;
                            case "RCUSTEL":
                                bHis = false;
                                bHis = checkForRCUSTEL(Ruleset_Id, drr[iRowCount]["af_row_id"].ToString(), dr["af_row_id"].ToString(), Operation);
                                break;
                            case "RCUBOR":
                                bHis = false;
                                bHis = checkForRCUBOR(Ruleset_Id, drr[iRowCount]["af_row_id"].ToString(), dr["af_row_id"].ToString(), Operation);
                                break;
                            case "RCUBORSTEL":
                                bHis = false;
                                bHis = checkForRCUBORSTEL(Ruleset_Id, drr[iRowCount]["af_row_id"].ToString(), dr["af_row_id"].ToString(), Operation);
                                break;
                        }
                        if (bHis)
                            addWorkflowHistory(Ruleset_Id, Object_Id, drr[iRowCount], dr["af_row_id"].ToString(), dr["created_at"].ToString(), dr["created_by"].ToString());
                        drCurrentData = null;
                    }
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("checkRules : Error :" + ex.Message);
        }
    }

    public string getReportingToUser(string User_afrowid, string Target_Title,int IterationNumber)
    {
        string sUser = "";
        try
        {
            if (IterationNumber <= dsWorkflow.Tables["sy_usr"].Rows.Count)
            {
                DataRow[] drr = dsWorkflow.Tables["sy_usr"].Select("af_row_id='" + User_afrowid + "'");

                if (drr.Length > 0)
                {
                    string sTitle_afrowid = drr[0]["title"].ToString();
                    //string sTitle = getColumnValue("sy_org_structure", "af_row_id", sTitle_afrowid, "title").ToLower();

                    if (sTitle_afrowid == "") return sUser;

                    if (sTitle_afrowid == Target_Title)
                        sUser = User_afrowid;
                    else
                        sUser = getReportingToUser(drr[0]["reporting_to"].ToString(), Target_Title, IterationNumber + 1);
                }
            }
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("getReportingToTitle : Error :" + ex.Message);
        }
        return sUser;
    }

    private void addWorkflowHistory(string Ruleset_Id, string Object_Id, DataRow drRule, string Key_Value, string object_rec_created_at, string object_rec_created_by)
    {
        try
        {
            //string sRuleTitle = getColumnValue("sy_work_item", "rule_id", drRule["af_row_id"].ToString(), "title");
            //string sRuleMessage = getColumnValue("sy_work_item", "rule_id", drRule["af_row_id"].ToString(), "message");
            getWorkitem_User(drRule);
            if (drRuleChange != null)
                drRule = drRuleChange;
            ScreenReader SR = new ScreenReader();
            string sAF_ROW_ID = SR.getHashKey();  // Added by srivatsan on June 15 2009 for owner id field
            string sSql = "insert into sy_workflow_history (ruleset_id, rule_id, object_id, pageset_id, menu_id, key_value, status, source_title, target_title, comments,is_active, af_row_id, created_by,owner_id,modified_by, created_at, modified_at,workflow_history_ref,object_record_created_at,object_record_created_by) values ('"
                + Ruleset_Id + "','" + drRule["af_row_id"].ToString() + "','" + Object_Id + "','" + strPagesetRowId + "','" + strMenuRowId + "','" + Key_Value + "','Submitted','" + drRule["source_title"].ToString() + "','" + drRule["target_title"].ToString()
                + "',null" + /*sRuleTitle + " - " + sRuleMessage +*/ ",'1','" + sAF_ROW_ID + "','" + HttpContext.Current.Session["user_afrowid"].ToString() + "','" + HttpContext.Current.Session["user_afrowid"].ToString() + "','" + HttpContext.Current.Session["user_afrowid"].ToString() + "','"
                + DateTime.Now.ToUniversalTime().ToString() + "','" + DateTime.Now.ToUniversalTime().ToString() + "','" + SR.getHashKey() + "','" + object_rec_created_at + "','" + object_rec_created_by + "')";
            SqlCommand sqlComm = new SqlCommand(sSql);
            int iRet = HDD.ExecuteCmdObj(sqlComm);

            sSql = "insert into sy_workitem_user (ruleset_id, rule_id, object_id, pageset_id, menu_id, key_value, status, source_title, target_title, comments, for_user, af_row_id, created_by,owner_id, modified_by, created_at, modified_at,is_active,object_record_created_at,object_record_created_by) values ('"
                + Ruleset_Id + "','" + drRule["af_row_id"].ToString() + "','" + Object_Id + "','" + strPagesetRowId + "','"
                + strMenuRowId + "','" + Key_Value + "','Submitted','" + drRule["source_title"].ToString() + "','"
                + drRule["target_title"].ToString() + "',null" + ",'" + sWorkitem_User + "','"
                + sAF_ROW_ID + "','" + HttpContext.Current.Session["user_afrowid"].ToString() + "','" + HttpContext.Current.Session["user_afrowid"].ToString()
                + "','" + HttpContext.Current.Session["user_afrowid"].ToString() + "','"
                + DateTime.Now.ToUniversalTime().ToString() + "','" + DateTime.Now.ToUniversalTime().ToString() + "','1','" + object_rec_created_at + "','" + object_rec_created_by + "')";
            sqlComm = new SqlCommand(sSql);
            iRet = HDD.ExecuteCmdObj(sqlComm);
            sqlComm = null;
            SR = null;
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("addWorkflowHistory : Error :" + ex.Message);
        }
    }
    private void insertWorkflowHistory(DataRow dr)
    {
        try
        {
            PageInfoLoad PIL = new PageInfoLoad();
            DataSet dsPageInfo = PIL.GetPageSetPageCtrlInfo("eed8935a7731fd44"); // workflow_history
            PIL = null;
            DataTable dt = new DataTable("p_workflow_history");
            dt.Rows.Add(dr);
            DataSet dsInput = new DataSet();
            dsInput.Tables.Add(dt);
            Master objMaster = new Master();
            objMaster.ProcessOperation(dsPageInfo, dsInput, "INSERT");
            objMaster = null;
            dsPageInfo = null;
            dsInput = null;
            dt = null;
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("insertWorkflowHistory : Error :" + ex.Message);
        }
    }

    private string getColumnValue(string Tablename, string whereFieldname, string Value, string Fieldname)
    {
        string sValue = "";
        try
        {
            if (dsWorkflow.Tables.Contains(Tablename))
            {
                DataRow[] drr = dsWorkflow.Tables[Tablename].Select(whereFieldname + "='" + Value.Replace("'", "''") + "'");
                if (drr.Length > 0)
                    sValue = drr[0][Fieldname].ToString();
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("getColumnValue : Error :" + ex.Message);
        }
        return sValue;
    }

    private string getColumnValue(string Tablename, string whereFieldname, string Value, string Fieldname, string TableName1)
    {
        string sValue = null;
        try
        {
            if (dsWorkflow.Tables.Contains(Tablename))
            {
                DataRow[] drr = dsWorkflow.Tables[Tablename].Select(whereFieldname + "='" + Value.Replace("'", "''") + "'");
                if (drr.Length > 0)
                    sValue = drr[0][Fieldname].ToString();
                else
                {
                    if (dsWorkflow.Tables.Contains(TableName1))
                    {
                        drr = dsWorkflow.Tables[TableName1].Select(whereFieldname + "='" + Value.Replace("'", "''") + "'");
                        if (drr.Length > 0)
                            sValue = drr[0][Fieldname].ToString();
                    }
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("getColumnValue : Error :" + ex.Message);
        }
        return sValue;
    }

    private string getValueFromDB(string Tablename, string ColumnName, string Fetch, string Value)
    {
        string sRet = "";
        try
        {
            string sSQL = "select " + Fetch + " from " + Tablename + " where " + ColumnName + "='" + Value.Replace("'", "''") + "'";
            sRet = HDD.GetColumnValue(sSQL);
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("getValueFromDB : Error :" + ex.Message);
        }
        return sRet;
    }

    private string getPageset(string Object_afrowid)
    {
        string sPgs_id = "";
        try
        {
            string sObject_id = getColumnValue("sy_obj", "af_row_id", Object_afrowid, "object_id");

            string sSql = "select * from sy_pgs_mem where object_id = '" + sObject_id + "'";
            DataTable dtPgs = HDD.GetDataTable(sSql);
            sSql = "select role_id from sy_usr_rol where user_id='" + HttpContext.Current.Session["user_afrowid"].ToString() + "'";
            string sRole_id = HDD.GetColumnValue(sSql);
            sSql = "select * from sy_obj_acc where object_id='" + sObject_id + "' and role_id='" + sRole_id + "'";
            DataTable dtRole = HDD.GetDataTable(sSql);

            if (dtRole.Columns.Count > 0)
            {
                strMenuRowId = HDD.GetColumnValue("select af_row_id from sy_mnu where pageset_id='" + dtPgs.Rows[0]["pageset_id"].ToString() + "'");
                //strPagesetRowId = dtPgs.Rows[0]["pageset_id"].ToString();
                //sPgs_id = HDD.GetColumnValue("select pageset_id from sy_pgs where af_row_id='" + strPagesetRowId + "'");
                //strMenuRowId = HDD.GetColumnValue("select af_row_id from sy_mnu where pageset_id='" + sPgs_id + "'");
            }
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("getPageset : Error :" + ex.Message);
        }
        return sPgs_id;
    }

    private void getWorkitem_User(DataRow drRule)
    {
        try
        {
            string sTarget = getColumnValue("rules", "af_row_id", drRule["af_row_id"].ToString(), "Target").ToLower();
            string sTarget_Title = getColumnValue("rules", "af_row_id", drRule["af_row_id"].ToString(), "target_title").ToLower();
            string sBased_On = getColumnValue("sy_workflow_ruleset", "af_row_id", drRule["ruleset"].ToString(), "based_on").ToLower();

            if (sTarget == "user_from_field")
            {
                string sAttrib_Id = getColumnValue("sy_obj_att", "af_row_id", sTarget_Title, "attrib_id");
                sWorkitem_User = getColumnValue("sy_usr", "af_row_id", drCurrentData[sAttrib_Id].ToString(), "af_row_id");
                if (sWorkitem_User == "")
                    sWorkitem_User = getColumnValue("sy_usr", "user_id", drCurrentData[sAttrib_Id].ToString(), "af_row_id");
            }
            else if (sTarget == "user")
                sWorkitem_User = getColumnValue("rules", "af_row_id", drRule["af_row_id"].ToString(), "target_title");
            else if (sTarget == "title")
            {
                string sSkip_Rule = getColumnValue("sy_workflow_ruleset", "af_row_id", drRule["ruleset"].ToString(), "skip_title").ToLower();
                if (sSkip_Rule == "true")
                    sWorkitem_User = getTargetUserBasedOnRule(drRule["af_row_id"].ToString());
                else if (sSkip_Rule == "false" || sSkip_Rule == "")
                {
                    string sTempUser = getColumnValue("sy_usr", "af_row_id", HttpContext.Current.Session["user_afrowid"].ToString(), "reporting_to");
                    string sTempTitle = getColumnValue("sy_usr", "af_row_id", sTempUser, "title");
                    if (sTarget_Title == sTempTitle) sWorkitem_User = sTempUser;

                    sWorkitem_User = getColumnValue("sy_usr", "af_row_id", HttpContext.Current.Session["user_afrowid"].ToString(), "reporting_to");
                }
            }

            bool workitemForSameUser = Convert.ToBoolean(HDD.GetColumnValue("select mem_value1 from sy_acr_mem where acr_id = 'ed7b9ed9e0398d20'"));
            if (!workitemForSameUser) // Added by 'Imran Gani' on 19-Mar-2013, to allow workitem for same user (based on user from field).
                if (sWorkitem_User == HttpContext.Current.Session["user_afrowid"].ToString())
                {
                    getPreviousOrNextRuleId(drRule, 1);
                    getWorkitem_User(drRuleChange);
                }

            string sTemp = getColumnValue("sy_usr", "af_row_id", sWorkitem_User, "af_row_id");
            //if  (sTemp == "")
            //    sWorkitem_User = "650a333596bbf348";
            //if (sWorkitem_User == "")
            //    sWorkitem_User = "650a333596bbf348";
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("getWorkitem_User : Error :" + ex.Message);
        }
    }

    private string getTargetUserBasedOnRule(string Rule_Id)
    {
        string sUser = "";
        try
        {
            string sTarget_Title = getColumnValue("sy_workflow_rules", "af_row_id", Rule_Id, "target_title");
            sUser = getReportingToUser(HttpContext.Current.Session["user_afrowid"].ToString(), sTarget_Title,1);
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("getTargetTitleBasedOnRule : Error : " + ex.Message);
        }
        return sUser;
    }

    private string getPreviousOrNextRuleId(DataRow drRule, int iRuleNo)
    {
        string sReturn = "";
        try
        {
            DataRow[] drr = dsWorkflow.Tables["rules"].Select("ruleset='" + drRule["ruleset"].ToString() + "'");
            int iMaxSeq = drr.Length;
            int iSeq = int.Parse(getColumnValue("rules", "af_row_id", drRule["af_row_id"].ToString(), "sequence"));
            if (iSeq < iMaxSeq) iSeq = iSeq + iRuleNo;
            drr = dsWorkflow.Tables["rules"].Select("ruleset='" + drRule["ruleset"].ToString() + "' and sequence ='" + iSeq + "'");
            if (drr.Length > 0)
            {
                drRuleChange = drr[0];
                sReturn = drr[0]["af_row_id"].ToString();
            }
        }

        catch (Exception ex)
        {
            sReturn = drRule["rule_id"].ToString();
            LogWriter.WriteLog("getPreviousOrNextRuleId : Error :" + ex.Message);
        }
        return sReturn;
    }
}
